<?php


namespace App\models;


use Consts\RedisKey;
use Helper\Output;
use Helper\Mysql;
use Helper\Redis;
use Helper\Reg;

class CustomerSession
{


    /**
     * 创建会话
     * @param $auid
     * @param $uid
     * @return bool
     * @throws \Exception
     */
    static public function createSession($auid,$uid){

        $sess = Mysql::getInstance()
            ->where('auid',$auid)
            ->where('uid',$uid)
            ->getOne('customer_session');
        $ip = Redis::getInstance()->hGet(RedisKey::CUSTOMER_NOW_SESS_IP ,'uid:'.$uid );
        $data = [
            'auid' => $auid,
            'uid' => $uid,
            'create_at' => time(),
            'is_first' => $sess?0:1,
            'ip'        => $ip?:0
        ];

        $res = Mysql::getInstance()
            ->insert("customer_session",$data);
        if(!$res){
            return false;
         }

        $sessInfo = [
            'sessid' => Mysql::getInstance()->getInsertId() ,
            'create_at'=> time(),
            'sessip' => $ip,
            'user'=>  Mysql::getInstance()->where('id',$uid)->getOne('customer') ,
            'unread_count'=> 1
        ];

        //加入到客服在线会话列表
        Redis::getInstance()->hSet(RedisKey::online_customer_list($auid),'uid:'.$uid,json_encode($sessInfo));
        //推送给客服
        Reg::getInstance()->get('server')->push(FdManager::getFdByAuid($auid),Output::json(2001,$sessInfo));
        //给用户推送一条默认消息
        Session::pushChatMessage( $sessInfo['sessid'] ,$auid ,$uid ,'您好,请问有什么需要帮助?',2005);

        return  $sessInfo['sessid'];

    }

}